package sys.useful;

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.channels.FileChannel;
import java.sql.Time;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableCellRenderer;
import org.jdesktop.swingx.JXDatePicker;
import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;

public class Utils {
    
    
    public static void mascaraData(final JXDatePicker c) {        
        c.setFormats("dd/MM/yyyy");
        c.getEditor().addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {
                super.keyTyped(e);

                String chr = String.valueOf(e.getKeyChar());
                c.getEditor().setBackground(Params.COR_CAMPO_NORMAL);

                if (!chr.matches("^\\d{1}$")) {
                    e.consume();
                }

                if ((c.getEditor().getText().length() == 2 || c.getEditor().getText().length() == 5) && e.getKeyChar() != e.VK_BACK_SPACE) {
                    c.getEditor().setText(c.getEditor().getText() + "/");
                }
            }
        });        
        c.getEditor().setText(null);        
        c.getEditor().setDocument(new FixLength(10));
    }

    public static void autoComplete(JComboBox combo) {
        AutoCompleteDecorator.decorate(combo);
    }

    public static Time convertHora(String hora) {
        Time time = null;
        try {
            SimpleDateFormat formatador = new SimpleDateFormat("HH:mm");
            Date data = formatador.parse(hora);
            time = new Time(data.getTime());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return time;
    }

    public static void corEntreLinhas(JTable tabela, final int coluna, final Color corLinha1, final Color corLetra1, final Color corLinha2, final Color corLetra2, final String paramentro) {
        tabela.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                //pegando o valor da coluna 2
                Object ref = table.getValueAt(row, coluna);
                //Coloca cor em todas as linhas,COLUNA(4)
                if (ref != null && ref.toString().equals(paramentro)) {
                    setBackground(corLinha1);//Altera para esta cor. 
                    setForeground(corLetra1);
                } else {
                    setBackground(corLinha2);
                    setForeground(corLetra2);
                }
                return this;
            }
        });
    }
    
    public static void corEntreLinhas(JTable tabela, final int coluna, final Color corLinha1, final Color corLetra1, final Color corLinha2, final Color corLetra2, final int paramentro) {
        tabela.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                int ref = Integer.parseInt(table.getValueAt(row, coluna).toString());
                
                if (ref < paramentro) {
                    setBackground(corLinha1);//Altera para esta cor. 
                    setForeground(corLetra1);
                } else {
                    setBackground(corLinha2);
                    setForeground(corLetra2);
                }
                return this;
            }
        });
    }

    public static void corLinhasSelecionada(JTable tabela, final Color corLinha1, final Color corLetra1) {
        tabela.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() {
            @Override
            public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
                super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
                setBackground(corLinha1);
                setForeground(corLetra1);
                return this;
            }
        });
    }

    public static void naoRedimensionar(JFrame frame) {
        frame.setResizable(false);
    }

    public static void naoRedimensionar(JDialog dialog) {
        dialog.setResizable(false);
    }

    public static void maximizarDialog(JDialog janela) {
        Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
        screen = new Dimension((int) screen.getWidth(), (int) screen.getHeight() - 50);
        janela.setSize(screen);
        janela.setLocationRelativeTo(null);
    }

    public static void maximizarAltura(JDialog janela) {
        Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
        screen = new Dimension(janela.getWidth(), (int) screen.getHeight() - 50);
        janela.setSize(screen);
        janela.setLocationRelativeTo(null);
    }

    public static void maximizarFrame(JFrame janela) {
        Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
        screen = new Dimension((int) screen.getWidth(), (int) screen.getHeight() - 50);
        janela.setSize(screen);
        janela.setLocationRelativeTo(null);
    }

    public static void notSelectMultipleRows(JTable e) {
        e.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    }

    public static void SelectMultipleRows(JTable e) {
        e.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
    }

    public static void maximumAndMinimumColumnSizeTable(JTable e, int column, int max, int min) {
        e.getColumnModel().getColumn(column).setMinWidth(min);
        e.getColumnModel().getColumn(column).setMaxWidth(max);
    }

    public static void centralizar(JDialog janela) {
        janela.setLocationRelativeTo(null);
    }

    public static void centralizar(JFrame janela) {
        janela.setLocationRelativeTo(null);
    }

    public static void configTabela(JTable tabela, int[] largura) {
        tabela.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

        for (int i = 0; i < largura.length; i++) {
            tabela.getColumnModel().getColumn(i).setPreferredWidth(largura[i]);

            if (largura[i] <= 0) {
                tabela.getColumnModel().getColumn(i).setMinWidth(0);
                tabela.getColumnModel().getColumn(i).setMaxWidth(0);
            }
        }
    }

    public static Date convertData(String date) {
        Date data = null;
        try {
            data = new SimpleDateFormat("dd/MM/yyyy").parse(date);
        } catch (ParseException ex) {
            //Msg.erro(null, "Erro ao converter data!!!\n\n" + ex.getMessage());
        }
        return data;
    }

    public static Date convertDataTime(String date) {
        Date data = null;
        try {
            data = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").parse(date);
        } catch (ParseException ex) {
            ex.printStackTrace();  //Msg.erro(null, "Erro ao converter data!!!\n\n" + ex.getMessage());
        }
        return data;
    }

    public static Date convertDataAtual(String date) {
        Date data = null;
        try {
            data = new SimpleDateFormat("dd/MM/yyyy").parse(date);
        } catch (ParseException ex) {
            ex.printStackTrace();  //Msg.erro(null, "Erro ao converter data!!!\n\n" + ex.getMessage());
        }
        return data;
    }

    public static String convertDateTime(Date date) {
        return new SimpleDateFormat("dd/MM/yyyy HH:mm:ss").format(date);
    }

    public static String convertData(Date date) {
        return new SimpleDateFormat("dd/MM/yyyy").format(date);
    }

    public static String convertData(Date date, String format) {
        return new SimpleDateFormat(format).format(date);
    }

    public static java.sql.Date convert(java.util.Date var) {
        int day = var.getDate();
        int mom = var.getMonth();
        int year = var.getYear();
        return new java.sql.Date(year, mom, day);
    }

    public static void copyFile(String srcFrom, String srcTo) throws IOException {
        if (srcFrom.equalsIgnoreCase(srcTo)) {
            return;
        }
        // Create channel on the source
        FileChannel srcChannel = new FileInputStream(srcFrom).getChannel();
        // Create channel on the destination
        FileChannel dstChannel = new FileOutputStream(srcTo).getChannel();
        // Copy file contents from source to destination
        dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
        // Close the channels
        srcChannel.close();
        dstChannel.close();
    }

    public static String getExtFile(String file) {
        String arr[] = file.split("[\\.]");

        if (arr.length < 2) {
            return null;
        }
        return arr[arr.length - 1].trim().toLowerCase();
    }

    public static void deleteFile(String srcFile) {
        File file = new File(srcFile);

        if (file.isFile()) {
            file.delete();
        }
    }

    public static void deleteTree(String srcFile) {
        File file = new File(srcFile);

        if (file.isFile()) {
            file.delete();
        } else {
            File files[] = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                deleteTree(files[i].getAbsolutePath());
            }
        }
    }

    public static boolean isEmail(String email) {
        String regexp = "^\\w+([\\.-]?\\w+)*@\\w+([\\.-]?\\w+)*(\\.\\w{1,3})+$";
        return email.matches(regexp);
    }

    public static boolean isCPF(String cpf) {
        boolean retorno = true;

        if (cpf.matches("^\\d{3}\\.\\d{3}\\.\\d{3}-\\d{2}$")) {
            try {
                cpf = cpf.replace(".", "");
                cpf = cpf.replace("-", "");

                String cpfV = "";
                for (int i = 0; i <= 9; i++) {
                    cpfV = "";
                    for (int j = 1; j <= 11; j++) {
                        cpfV += i;
                    }
                    if (cpfV.equals(cpf)) {
                        return false;
                    }
                }

                int digito[] = new int[11];
                int dvInformado = Integer.parseInt(cpf.substring(9, 11));

                for (int i = 0; i <= 8; i++) {
                    digito[i] = Integer.parseInt(cpf.substring(i, i + 1));
                }

                int posicao = 10;
                int soma = 0;

                for (int i = 0; i <= 8; i++) {
                    soma = (soma + digito[i] * posicao);
                    posicao = (posicao - 1);
                }

                digito[9] = (soma % 11);

                if (digito[9] < 2) {
                    digito[9] = 0;
                } else {
                    digito[9] = (11 - digito[9]);
                }

                posicao = 11;
                soma = 0;

                for (int i = 0; i <= 9; i++) {
                    soma = (soma + digito[i] * posicao);
                    posicao = (posicao - 1);
                }

                digito[10] = (soma % 11);

                if (digito[10] < 2) {
                    digito[10] = 0;
                } else {
                    digito[10] = (11 - digito[10]);
                }

                int dv = (digito[9] * 10 + digito[10]);

                if (dv != dvInformado) {
                    retorno = false;
                }
            } catch (Exception e) {
                retorno = false;
            }
        } else {
            retorno = false;
        }

        return retorno;
    }

    public static boolean isCNPJ(String cnpj) {
        boolean retorno = true;

        if (!cnpj.matches("\\d{2}\\.\\d{3}\\.\\d{3}/\\d{4}-\\d{2}")) {
            return false;
        }

        cnpj = cnpj.replace(".", "");
        cnpj = cnpj.replace(".", "");
        cnpj = cnpj.replace("-", "");
        cnpj = cnpj.replace("/", "");

        int a[] = new int[14];
        int x = 0, b = 0;
        int c[] = {6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2};

        for (int i = 0; i < 12; i++) {
            a[i] = Integer.parseInt(cnpj.substring(i, i + 1));
            b += (a[i] * c[i + 1]);
        }

        if ((x = b % 11) < 2) {
            a[12] = 0;
        } else {
            a[12] = (11 - x);
        }

        b = 0;
        for (int y = 0; y < 13; y++) {
            b += (a[y] * c[y]);
        }

        if ((float) (x = b % 11) < 2) {
            a[13] = 0;
        } else {
            a[13] = (11 - x);
        }

        int pos12 = Integer.parseInt(cnpj.substring(12, 13));
        int pos13 = Integer.parseInt(cnpj.substring(13, 14));

        if ((pos12 != a[12]) || (pos13 != a[13])) {
            retorno = false;
        }

        return retorno;
    }
    
    public static void fixarTamanho_TextField(JTextField c, int tamanho) {
        c.setDocument(new FixLength(tamanho));
    }
    
    public static void fixarTamanho_TextArea(JTextArea c, int tamanho) {
        c.setDocument(new FixLength(tamanho));
    }
    
    
    public static void setLookAndFeel(Component tela) {
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
            SwingUtilities.updateComponentTreeUI(tela);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // metodo que retorna o intervalo de dias entre duas datas  
    public static String contaDias(String dataInicialBR, String dataFinalBR) throws ParseException {

        DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        df.setLenient(false);

        Date dataInicio = df.parse(dataInicialBR);
        Date dataFim = df.parse(dataFinalBR);
        long dt = (dataFim.getTime() - dataInicio.getTime()) + 3600000;
        Long diasCorridosAnoLong = (dt / 86400000L);

        Integer diasDecorridosInt = Integer.valueOf(diasCorridosAnoLong.toString());

        String diasDecorridos = String.valueOf(diasDecorridosInt); //Sem numeros formatados;    

        return diasDecorridos;

    }

// método para pegar a data do dia  
    public static String getDataDiaBr() {
        GregorianCalendar calendario = new GregorianCalendar();
        int dia = calendario.get(calendario.DAY_OF_MONTH);
        int mes = calendario.get(calendario.MONTH) + 1;
        int ano = calendario.get(calendario.YEAR);
        String dataIguana = String.valueOf(dia + "/" + mes + "/" + ano);
        DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
        String diaIguana = df.format(new Date());
        return diaIguana;
    }

// agora para calcular a idade  
    public static BigDecimal calculaIdade(String dataDoMeuNascimento) throws ParseException {
        BigDecimal qtdDias = new BigDecimal(contaDias(dataDoMeuNascimento, getDataDiaBr()));
        BigDecimal ano = new BigDecimal(365.25);
        BigDecimal idade = qtdDias.divide(ano, 0, RoundingMode.DOWN);

        return idade;
    }
}
